// pages/home/city/city.js
const { getHomeHttp } = require("../../../utils/http")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        indexList: [],
        cities: {},
        hotCities: [],
        newCities: [],
        city: '',
        newCity: ''
    },

    handleAddNewCity(e) {
        let id = e.currentTarget.dataset.aid
        let cities = this.data.cities
        let newCities = this.data.newCities
        let newCity
        for (const key in cities) {
            cities[key].forEach(item => {
                if (item.id !== id) return
                newCities.forEach(val => {
                    if (val.id === id) newCities.splice(newCities.indexOf(val), 1)
                })
                newCity = item.name
                newCities.unshift(item)
            })
        }
        this.setData({ newCities, newCity })
        this.goback()
        wx.setStorage({ key: 'newCities', data: newCities, })
    },
    goback() {
        var pages = getCurrentPages()
        var prevPage = pages[pages.length - 2]
        prevPage.setData({
            newCity: this.data.newCity
        })
        wx.navigateBack({
            delta: 0,
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        let city = options.city
        let cities = await getHomeHttp.getCityHttp()
        let hotCities = cities.data.res[0].hotCities
        cities = cities.data.res[0].cities
        let indexList = this.data.indexList
        for (const key in cities) {
            indexList.push(key)
        }
        this.setData({ hotCities, cities, indexList, city, newCities: wx.getStorageSync('newCities') || [] })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})